<template>
	<view>
		<view class="seacher-tit">
			<view class="seacher-input">
				<text class="greencircle green"></text>
				<input id="1" v-model="start_point" :focus="isFocusStart" placeholder="输入起点" @input="onPress" confirm-type="search"
				 @confirm="bindconfirm" @click="oncheck" />
			</view>
			<view @click="exchange" class="sub">
				<image class="sub-change" src="../../static/icon_change.png"></image>
			</view>
			<view class="seacher-input">
				<text class="greencircle pick"></text>
				<input id="2" v-model="keywords" :focus="isFocusEnd" confirm-type="search" @confirm="bindconfirm" @input="onPress"
				 @click="oncheck" placeholder="你要去哪儿" />
			</view>
		</view>

		<view class="search-container">
			<view style="height: 20px;background: #f1f1f1;"></view>
			<view class="list-route" v-if="checkout == 1">
				<view @click="checkStart" class="list-item" v-if="status == 1">
					<image class="icon-img" src="../../static/icon_location.png" />
					<view class="item">
						<text style="margin: 5px 0px;">我的位置</text>
					</view>
				</view>
				<view @click="checkStartPoint" class="list-item-adr" v-for="(item,index) in sList" :data-keywords="index">
					<image class="icon-img" src="../../static/icon_history.png" />
					<view class="item">
						<view class="address-top">{{item.name}}</view>
						<view class="address-foot">{{item.address}}</view>
					</view>
				</view>
				<view @click="cleanStartAdr" v-if="sList.length > 1" class="item">
					<text class="clean">清除历史记录</text>
				</view>
			</view>

			<view class="list-route" v-if="checkout == 0">
				<view @click="checkHistory" class="list-item" v-for="(item,index) in history" :data-keywords="index">
					<image class="icon-img" src="../../static/icon_history.png" />
					<view class="item">
						<text class="start-point">{{item.start_name}}</text>
						<uni-icon class="icon" type="arrowthinright"></uni-icon>
						<text>{{item.end_name}}</text>
					</view>
				</view>
				<view @click="cleanHistory" v-if="history.length > 1" class="item">
					<text class="clean">清除历史记录</text>
				</view>
			</view>

			<view class="list-route">
				<view @click="selected" class="list-item" v-if="checkout == 3" v-for="(item,index) in tips" :data-keywords="index">
					<image class="icon-img" src="../../static/icon_location.png" />
					<view class="item">
						<view class="address-top">{{item.name}}</view>
						<view v-if="item.address.length > 0" class="address-foot">{{item.address}}</view>
					</view>
				</view>
			</view>

			<view class="list-route" v-if="checkout == 4">
				<navigator :url="'/pages/routePlanning/transport?idx='+index" class="list-item" v-for="(item,index) in transits"
				 :keywords="index">
					<view>
						<text class="duration">{{item.duration}}</text>
						<view>
							<view class="transport" v-for="(name,idx) in item.transport">
								<view class="transport-name">
									<text>{{name}}</text>
								</view>
								<view v-if="idx!=item.transport.length-1" class="triangle">
									<text class="triangle_border_right"></text>
								</view>
							</view>
						</view>
						<view class="text-tags">
							<view class='tags'>
								<text class="text">{{item.via_num}}站</text>
								<text class="roundes"></text>
							</view>
							<view class='tags' v-if="item.cost.length > 0">
								<text class="text">{{item.cost}}元</text>
								<text class="roundes"></text>
							</view>
							<view class="tags">
								<text class="text">{{item.segments[0].bus.buslines[0].departure_stop.name}}上车</text>
							</view>
						</view>
					</view>
				</navigator>
			</view>
		</view>
	</view>
</template>
<script>
	import uniIcon from '../../components/uni-icon/uni-icon.vue';
	import amapFile from '../../common/amap-wx.js';
	import config from '../../common/config.js';

	import {
		mapState,
		mapMutations
	} from 'vuex';

	const myAmapFun = new amapFile.AMapWX({
		key: config.Config.key
	});
	export default {
		components: {
			uniIcon
		},
		data() {
			return {
				checkout: 0,
				tips: [],
				start_point: "我的位置",
				keywords: '',
				distance: '',
				cost: '',
				status: 1,
				transits: [],
				history: [],
				sList: [],
				endPlace: {},
				isFocusStart: false,
				isFocusEnd: false
			}
		},
		computed: {
			...mapState([
				'place'
			]),
		},
		onLoad() {
			this.initDate();
			this.checkStart();
		},
		methods: {
			...mapMutations(['saveTransport', 'savePath', 'saveMarkers']),
			initDate: function(e) {
				let self = this;
				uni.getStorage({
					key: 'address',
					success: (res) => {
						self.history = res.data;
					},
				});
				uni.getStorage({
					key: 'sList',
					success: (res) => {
						self.sList = res.data;
					},
				});
			},
			oncheck: function(e) {
				this.checkout = 1;
				this.status = e.target.id;
			},
			onPress: function(e) {
				let self = this;
				let value = e.detail.value;
				//如果输入值是否为空
				if (e.target.value.trim().length == 0) {
					self.checkout = 1;
					return;
				}
				myAmapFun.getInputtips({
					keywords: value,
					city: config.Config.city,
					location: self.place.location,
					success: function(data) {
						let status = e.target.id;
						if (data && data.tips) {
							if (e.target.value.length > 0) {
								status = 3;
							}
							self.status = e.target.id;
							self.tips = data.tips;
							self.checkout = status;
						}
					}
				})
			},
			selected: function(e) {
				let tips = this.tips,
					checkout = this.checkout,
					index = e.currentTarget.dataset.keywords,
					_self = this,
					status = this.status;
				if (tips[index].location.length == 0) {
					uni.showToast({
						title: "暂未查到公交线路...",
						icon: "none"
					});
					return;
				}
				let path = {
					name: tips[index].name,
					address: tips[index].district,
					location: tips[index].location
				};
				if (_self.status == 1) {
					_self.start_point = tips[index].name;
					_self.savePath(path);
				} else {
					_self.endPlace = path;
					_self.keywords = tips[index].name;
				}
				_self.checkStartPlace(path);
				_self.checkSearch();
			},
			//确认搜索
			bindconfirm: function(e) {
				let value = e.detail.value;
				let arr = this.tips;
				let _self = this;
				
				if (this.status == 1) {
					if (this.start_point == ''){
						uni.showToast({
							title: "请输入起始地址",
							icon: "none"
						});
						return;
					}
				} else {
					if (this.keywords == ''){
						uni.showToast({
							title: "请输入终点地址",
							icon: "none"
						});
						return;
					}
				}
				//查找指定的内容
				let data = arr.filter(function(p){
					return p.name === value;
				});
				if(data.length > 0){
					let path = {
						name: data[0].name,
						address: data[0].district,
						location: data[0].location
					};
					if (_self.status == 1) {
						_self.start_point = path.name;
						_self.savePath(path);
					} else {
						_self.endPlace = path;
						_self.keywords = path.name;
					}
					_self.checkStartPlace(path);
					_self.checkSearch();
				} else {
					uni.showToast({
						title: "未查找到结果",
						icon: "none"
					});
				}
			},
			getTransitRouter(start_local, end_local) {
				let that = this;
				myAmapFun.getTransitRoute({
					origin: start_local,
					destination: end_local,
					city: config.Config.city,
					success: function(data) {
						if (data && data.transits) {
							var transits = data.transits;
							for (var i = 0; i < transits.length; i++) {
								transits[i].cost = transits[i].cost.split('.')[0];
								var segments = transits[i].segments;
								transits[i].duration = secondToDate(transits[i].duration);
								transits[i].transport = [];
								transits[i].via_num = 0;
								transits[i].transit = transits[i].segments[0].bus.buslines[0].departure_stop.name;
								for (var j = 0; j < segments.length; j++) {
									if (segments[j].bus && segments[j].bus.buslines && segments[j].bus.buslines[0] && segments[j].bus.buslines[
											0].name) {
										let names = "";
										for (let k = 0; k < segments[j].bus.buslines.length; k++) {
											let str = segments[j].bus.buslines[k].name.replace(/[()-]/g, ",");
											let arr = str.split(',');
											segments[j].bus.buslines[k].start = arr[1];
											segments[j].bus.buslines[k].end = arr[3];
											segments[j].bus.buslines[k].direction = arr[0]
											segments[j].bus.buslines[k].duration = Math.floor(segments[j].bus.buslines[k].duration / 60);
											if (segments[j].bus.buslines.length - 1 == k) {
												names += arr[0]
											} else {
												names += arr[0] + '/';
											}
											transits[i].arrival_stop = segments[j].bus.buslines[k].arrival_stop;
										}
										transits[i].transport.push(names);
										transits[i].via_num += Number(segments[j].bus.buslines[0].via_stops.length + 1);
										transits[i].start_point = that.start_point;
										transits[i].end_point = that.endPlace.name;
										if (that.endPlace.name.indexOf('公交站') >= 0 && that.endPlace.name.indexOf(transits[i].arrival_stop.name) >=
											0) {
											transits[i].isShow = false;
										} else if (that.endPlace.name.indexOf('地铁站') >= 0 && that.endPlace.name.indexOf(transits[i].arrival_stop.name) >=
											0) {
											transits[i].isShow = false;
										} else {
											transits[i].isShow = true;
										}
									}
								}
							}
						}
						that.save_address();
						that.checkout = 4;
						that.transits = transits;
						that.saveTransport(transits);
					},fail: function(info) {
						uni.showToast({
							title: "无法查询到公交路线",
							icon: "none"
						});
					}
				})
			},
			//缓存搜索历史记录到本地
			save_address: function(val) {
				let result = uni.getStorageSync('address');
				let array = new Array();
				let place = {
					start_name: this.place.name,
					start_local: this.place.location,
					start_address: this.place.address,
					end_name: this.endPlace.name,
					end_local: this.endPlace.location,
					end_address: this.endPlace.address
				};
				if (result.length > 0) {
					let item = result.find(item => {
						return item.start_name == place.start_name && item.end_name == place.end_name;
					});
					if (typeof(item) == 'undefined') {
						array = result;
						array.push(place);
						uni.setStorageSync('address', array);
					}
				} else {
					array.push(place);
					uni.setStorageSync('address', array);
				}
			},
			//缓存起始位置
			checkStartPlace: function(path) {
				let list = uni.getStorageSync('sList');
				let arr = new Array();
				if (list.length > 0) {
					let item = list.find(item => {
						return item.location == path.location && path.location != this.place.location;
					});
					if (typeof(item) == 'undefined') {
						arr = list;
						arr.push(path);
						uni.setStorageSync('sList', arr);
					}
				} else {
					arr.push(path);
					uni.setStorageSync('sList', arr);
				}
			},
			exchange: function(e) {
				let _self = this;
				if (this.start_point == '' || this.keywords == '') {
					uni.showToast({
						title: "搜索内容为空",
						icon: "none"
					});
					return;
				}
				let start = _self.place;
				let end = _self.endPlace;
				let start_point = _self.start_point;
				let end_point = _self.keywords;
				_self.keywords = start_point;
				_self.start_point = end_point;
				_self.endPlace = start;
				_self.savePath(end);
				_self.checkSearch();
			},
			//点击搜索历史记录
			checkHistory: function(e) {
				let data = this.history,
					idx = e.currentTarget.dataset.keywords;
				this.keywords = data[idx].end_name;
				this.start_point = data[idx].start_name;
				let start_place = {
					name: data[idx].start_name,
					location: data[idx].start_local,
					address: data[0].start_address
				};
				let end_place = {
					name: data[idx].end_name,
					location: data[idx].end_local,
					address: data[0].end_address
				};
				this.savePath(start_place);
				this.endPlace = end_place;
				if (JSON.stringify(this.place) != '{}' && JSON.stringify(this.endPlace) != '{}') {
					this.getTransitRouter(this.place.location, this.endPlace.location);
				}
				let markers = [{
					iconPath: "../../static/icon_start.png",
					id: 0,
					latitude: this.place.location.split(',')[1],
					longitude: this.place.location.split(',')[0],
					width: 23,
					height: 27
				}, {
					iconPath: "../../static/icon_end.png",
					id: 0,
					latitude: this.endPlace.location.split(",")[1],
					longitude: this.endPlace.location.split(",")[0],
					width: 23,
					height: 27
				}];
				this.saveMarkers(markers)
			},
			//点击位置
			checkStartPoint: function(e) {
				let data = this.sList,
					idx = e.currentTarget.dataset.keywords,
					_self = this;
				let place = {
					name: data[idx].name,
					location: data[idx].location,
					address: data[idx].address
				};
				if (_self.status == 1) {
					_self.start_point = data[idx].name;
					_self.$store.state.place = place;
				} else {
					_self.endPlace = place;
					_self.keywords = data[idx].name;
				}
				_self.checkSearch();
			},
			checkStart: function(e) {
				let place = this.place;
				let _self = this;
				let key = config.Config.key;
				let MyAmapFun = new amapFile.AMapWX({
					key: key
				});
				MyAmapFun.getRegeo({
					iconPath: "../../lib/img/mapicon_navi_s.png", //定位图片自己找个图标
					iconWidth: 22,
					iconHeight: 32,
					success: function(data) {
						let place = {
							name: "我的位置",
							location: data[0].longitude + ',' + data[0].latitude,
							address: data[0].name
						};
						if(_self.status == 1) {
							_self.start_point = "我的位置";
							_self.longitude = data[0].longitude;
							_self.latitude = data[0].latitude;
							_self.savePath(place);
						}
						if(JSON.stringify(_self.endPlace) != '{}') {
							_self.checkSearch();
						}
					},
					fail: function(info) {}
				});
			},
			cleanHistory: function(e) {
				let _self = this;
				uni.showModal({
					content: '确认删除所有历史记录?',
					success: function(res) {
						if (res.confirm) {
							uni.removeStorageSync('address');
							_self.history = [];
						}
					}
				});
			},
			cleanStartAdr: function(e) {
				let _self = this;
				uni.showModal({
					content: '确认删除所有历史记录?',
					success: function(res) {
						if (res.confirm) {
							uni.removeStorageSync('sList');
							_self.sList = [];
						}
					}
				});
			},
			checkSearch: function(e) {
				let _self = this;
				if (JSON.stringify(_self.place) == '{}') {
					_self.isFocusStart = true;
					_self.checkout = 1;
					_self.status = 1;
					return;
				}
				//判断终点是否未选择地址
				if (JSON.stringify(_self.endPlace) == '{}') {
					_self.isFocusEnd = true;
					_self.checkout = 1;
					_self.status = 2;
					return;
				}
				//判断起点和终点位置是否相同
				if (_self.place.location == _self.endPlace.location) {
					uni.showToast({
						title: "起点与终点不能相同",
						icon: "none"
					});
					return;
				}
				//目的地不为空
				if (JSON.stringify(_self.place,) != '{}' && JSON.stringify(_self.endPlace) != '{}') {
					_self.getTransitRouter(_self.place.location, _self.endPlace.location);
				}
				let markers = [{
					iconPath: "../../static/icon_start.png",
					id: 0,
					latitude: _self.place.location.split(',')[1],
					longitude: _self.place.location.split(',')[0],
					width: 23,
					height: 27
				}, {
					iconPath: "../../static/icon_end.png",
					id: 0,
					latitude: _self.endPlace.location.split(",")[1],
					longitude: _self.endPlace.location.split(",")[0],
					width: 23,
					height: 27
				}];
				_self.saveMarkers(markers)
			}
		}
	}

	function secondToDate(result) {
		var h = Math.floor(result / 3600) < 10 ? Math.floor(result / 3600) : Math.floor(result / 3600);
		var m = Math.floor((result / 60 % 60)) < 10 ? Math.floor((result / 60 % 60)) : Math.floor((result / 60 % 60));
		if (h != 0) {
			return result = h + "时" + m + "分";
		} else {
			return result = m + "分钟";
		}
	}

	function uniq(array) {
		var temp = []; //一个新的临时数组
		for (var i = 0; i < array.length; i++) {
			if (temp.indexOf(array[i].end_point.name) == -1) {
				temp.push(array[i]);
			}
		}
		return temp;
	}
</script>
<style>
	.seacher-tit {
		background-color: #FFFFFF;
		position: fixed;
		left: 0px;
		overflow: hidden;
		-webkit-box-pack: justify;
		z-index: 999;
		transition-property: all;
		width: 100%;
	}

	.icon {
		font-weight: bold;
		font-size: 20px;
		color: #CDC8B1;
		width: 30px;
		text-align: center;
	}

	.search-container {
		padding-top: 120px;
	}

	.seacher-tit .seacher-input {
		padding: 0px 20px;
		-webkit-align-items: center;
		display: -webkit-flex;
		border-bottom: 1px solid #F4F4F4;
	}

	.seacher-tit .seacher-input text {
		width: 20px;
	}

	.seacher-tit .seacher-input input {
		width: 200px;
		height: 60px;
		line-height: 60px;
	}

	.greencircle:after {
		content: '';
		margin: 3px;
		display: table;
		width: 8px;
		height: 8px;
		border-radius: 50%;
	}

	.roundes:after {
		content: '';
		margin: 3px;
		display: table;
		width: 3px;
		height: 3px;
		border-radius: 50%;
		background: #666666;
		text-align: center;
	}

	.green:after {
		background: #43bba3;
	}

	.pick:after {
		background: #ff7f7f;
	}

	.list-route {
		background-color: #FFFFFF;
	}

	.list-item {
		padding: 0px 20px;
		-webkit-align-items: center;
		display: -webkit-flex;
		border-bottom: 1px solid #F4F4F4;
	}

	.height {
		height: 30px;
		line-height: 30px;
	}

	.list-item-adr {
		height: 60px;
		line-height: 60px;
		padding: 0px 20px;
		-webkit-align-items: center;
		display: -webkit-flex;
		border-bottom: 1px solid #F4F4F4;
	}

	.item {
		margin: 10px 5px;
		width: 90%;
	}

	.start-point {
		color: #CDC8B1;
	}

	.text-tags {
		position: relative;
		display: -webkit-flex;
		padding-top: 13px;
	}

	.address-top {
		font-size: 15px;
		color: #000000;
	}

	.address-foot {
		color: #666666;
		font-size: 14px;
		overflow: hidden;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-line-clamp: 1;
		-webkit-box-orient: vertical;
	}

	.icon-img {
		height: 18px;
		width: 18px;
	}

	.duration {
		font-weight: 600;
		font-size: 18px;
		color: #1F1F1F;
		height: 40px;
		line-height: 40px;
	}

	.transport {
		position: relative;
		display: inline-flex;
		padding: 5px 0px;
	}

	.transport-name {
		border: 2px solid #007AFF;
		border-radius: 10px;
		padding: 3px 9px;
	}

	.transport-name text {
		font-size: 13px;
		color: #007AFF;

	}

	.triangle {
		position: relative;
		display: inline-flex;
		top: 12px;
	}

	.triangle_border_right {
		width: 0px;
		height: 0px;
		border-width: 6px 0px 6px 12px;
		border-style: solid;
		border-color: transparent transparent transparent rgba(153, 153, 153, 1);
		/*透明 透明 透明 灰*/
		margin: 0px 10px;
	}

	.tags {
		position: relative;
		display: inline-flex;
		-webkit-align-items: center;
		padding: 0px 2px;
	}

	.tags .text {
		margin-right: 3px;
		color: #666666;
	}

	.sub {
		position: absolute;
		right: 23px;
		top: 50px;
		background: #FFFFFF;
	}

	.sub-change {
		display: block;
		height: 19px;
		width: 20px;
		transform: rotate(90deg);
	}

	.clean {
		text-align: center;
		display: block;
		height: 30px;
		line-height: 20px;
		color: #999999;
	}
</style>
